package com.mdx.zhizhao.controller;



import com.alibaba.dashscope.app.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mdx.zhizhao.domain.Response;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import com.qcloud.cos.utils.IOUtils;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.io.*;

@RestController
@RequestMapping(value = "/COSandAI" ,produces = {MediaType.APPLICATION_JSON_VALUE,MediaType.APPLICATION_XML_VALUE})
@CrossOrigin(origins = "http://localhost:5173")
public class COSandAI {
    public static String appCall(String context)
            throws ApiException, NoApiKeyException, InputRequiredException {
        ApplicationParam param = ApplicationParam.builder()
                // 若没有配置环境变量，可用百炼API Key将下行替换为：.apiKey("sk-xxx")。但不建议在生产环境中直接将API Key硬编码到代码中，以减少API Key泄露风险。
                .apiKey("sk-a366c2b70744440b96b9a81c569a7d93")
                .appId("dbc9b6633c354df09c55a6875c7c5951")
                .prompt(context)
                .build();

        Application application = new Application();
        ApplicationResult result = application.call(param);

        System.out.printf("text: %s\n",
                result.getOutput().getText());
        return result.getOutput().getText();
    }
    public static COSClient createCOSClient() {
//        String secretId = System.getenv("AKIDNcm95ELWlzIf5byQoHb0X3W9yv5BMh2L");
//        String secretKey = System.getenv("Rl2CKPRNE4vt0FVsFi5W2OrQ7udPFE5w");
        COSCredentials cred = new BasicCOSCredentials("AKIDNcm95ELWlzIf5byQoHb0X3W9yv5BMh2L", "Rl2CKPRNE4vt0FVsFi5W2OrQ7udPFE5w");
        ClientConfig clientConfig = new ClientConfig();
        clientConfig.setRegion(new Region("ap-nanjing"));
        return new COSClient(cred, clientConfig);
    }
    public static void update(String key,String resume) throws IOException {
        COSClient cosClient = createCOSClient();
        String bucketName = "red3and-1325710075";
//        String localFilePath = "/path/to/localFile";
//        File localFile = new File(localFilePath);
//        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
        File localFile = new File("test.txt");
        FileWriter fw = new FileWriter("test.txt",false);
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(resume);
        bw.close();
        fw.close();
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
        putObjectRequest.setStorageClass(StorageClass.Standard_IA);

        try {
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            System.out.println(putObjectResult.getRequestId());
        } catch (CosServiceException e) {
            e.printStackTrace();
        } catch (CosClientException e) {
            e.printStackTrace();
        } finally {
            cosClient.shutdown();
        }
    }

    public static String select(String key) throws IOException {
        COSClient cosClient = createCOSClient();
        String bucketName = "red3and-1325710075";
        COSObject cosObject = cosClient.getObject(new GetObjectRequest(bucketName, key));
        InputStream cosObjectInput = cosObject.getObjectContent();
        byte[] bytes = IOUtils.toByteArray(cosObjectInput);
        String b = new String(bytes);
        System.out.println(b);
        return b;
//        JSONObject jsonObject1 = JSON.parseObject(b);
    }
    @PostMapping("/Generate")
    public Response<JSONObject> Generate(@RequestParam("context") String context,
                                         @RequestParam("id") String id) throws IOException {
        String b="";
        try {
            String resume=appCall(context);
            String s="{context:"+context+",resume:"+resume+",\"status\":1}";
            update(id,s);
            b=select(id);
            JSONObject jsonObject1 = JSON.parseObject(b);
            Response<JSONObject> response = new Response();
            response.s(jsonObject1,"1");
            return response;
        } catch (NoApiKeyException e) {
            throw new RuntimeException(e);
        } catch (InputRequiredException e) {
            throw new RuntimeException(e);
        }
    }
    @PostMapping("/selectByID")
    public Response<JSONObject> selectByID(@RequestParam("id") String id){
        String b="";
        try {
            b=select(id);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        JSONObject jsonObject1 = JSON.parseObject(b);
        Response<JSONObject> response = new Response();
        response.s(jsonObject1,"1");
        return response;
    }

    @PostMapping("/Save")
    public Response<JSONObject> Save(@RequestParam("context") String context,
                                         @RequestParam("id") String id) throws IOException {
        String b="";
        update(id,context);
        b=select(id);
        JSONObject jsonObject1 = JSON.parseObject(b);
        Response<JSONObject> response = new Response();
        response.s(jsonObject1,"1");
        return response;
    }

    public static void main(String[] args) throws IOException, NoApiKeyException, InputRequiredException {
//        String context = "";
//        String key ="";
//        String resume = appCall(context);
//        update(key,resume);
        select("9");
        update("9","123");
        select("9");
    }
}